package com.example.asus.happy;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asus.happy.service.address.Address;
import com.example.asus.happy.service.application.MyApplication;
import com.example.asus.happy.service.finaldata.FinalData;
import com.example.asus.happy.service.model.Content;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.example.asus.happy.R.id.discussBtn;
import static com.example.asus.happy.R.id.laudBtn;


public class MyHomeActivity extends Fragment implements View.OnClickListener{

    private SwipeRefreshLayout mSwipeLayout,id_swipe_ly_comment,id_swipe_ly_commentI;
    private ViewPager viewPager;
    private Context mContext;//上下文
    private Button iSendBtn,iCommentBtn,commentIBtn,iLaudBtn,laudIBtn;
    private String userName;
    private String isendUrl;//我发的请求地址
    private String icommenUrl;//我评的请求地址
    private String commeniUrl;//评我的请求地址
    private TextView userNameTV;//用户名
    private TextView updatePwdTV,setTV;//修改密码
    private List<View> mViews = new ArrayList<View>();
    private PagerAdapter mAdapter;
    private List<Content> list;
    private MyAdapter myAdapter;
    private CommentAdapter commentAdapter;
    private Intent intent;
    private ListView jokeList,commentList,commentIList;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();
        userName = ((MyApplication) getActivity().getApplication()).getUserName();

    }


    //处理下拉刷新的Handler
    private Handler mHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case 1:
                    mSwipeLayout.setRefreshing(false);
                    break;
                case 2:
                    id_swipe_ly_comment.setRefreshing(false);
                    break;
                case 3:
                    id_swipe_ly_commentI.setRefreshing(false);
                    break;
            }
        };
    };


    //处理显示我发的内容的handler
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String response = (String)msg.obj;
                    list = getCarte(response);
                    myAdapter = new MyAdapter();
                    jokeList.setAdapter(myAdapter);
                    //刷新成功
                    mHandler.sendEmptyMessage(FinalData.ONE_INT);
                    break;
                default:
                    break;
            }
        }

    };

    //处理显示我评的内容的handler
    private Handler handler1 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String response = (String)msg.obj;
                    list = getCarte(response);
                    commentAdapter = new CommentAdapter();
                    commentList.setAdapter(commentAdapter);
                    //刷新成功
                    mHandler.sendEmptyMessage(2);
                    break;
                default:
                    break;
            }
        }

    };


    //处理显示评我的内容的handler
    private Handler handler2 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String response = (String)msg.obj;
                    list = getCarte(response);
                    commentAdapter = new CommentAdapter();
                    commentIList.setAdapter(commentAdapter);
                    //刷新成功
                    mHandler.sendEmptyMessage(3);
                    break;
                default:
                    break;
            }
        }

    };


    private void HttpPostRequest(final String isendUrl){
        //处理显示我发的内容的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(isendUrl);
                List<NameValuePair> carteList = new ArrayList<NameValuePair>();
                try{
                    httpPost.setEntity(new UrlEncodedFormEntity(carteList,FinalData.CODE));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == FinalData.TWO_HUNDRED){
                        HttpEntity httpEntity = httpResponse.getEntity();
                        String count = EntityUtils.toString(httpEntity,FinalData.CODE);
                        Message message = new Message();
                        message.what = FinalData.ZERO_INT;
                        message.obj = count.toString();
                        handler.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void HttpPostRequest1(final String icommentUrl){
        //处理显示我评的内容的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(icommentUrl);
                List<NameValuePair> carteList = new ArrayList<NameValuePair>();
                try{
                    httpPost.setEntity(new UrlEncodedFormEntity(carteList,FinalData.CODE));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == FinalData.TWO_HUNDRED){
                        HttpEntity httpEntity = httpResponse.getEntity();
                        String count = EntityUtils.toString(httpEntity,FinalData.CODE);
                        Message message = new Message();
                        message.what = FinalData.ZERO_INT;
                        message.obj = count.toString();
                        handler1.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void HttpPostRequest2(final String commeniUrl){
        //处理显示评我的内容的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(commeniUrl);
                List<NameValuePair> carteList = new ArrayList<NameValuePair>();
                try{
                    httpPost.setEntity(new UrlEncodedFormEntity(carteList,FinalData.CODE));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == FinalData.TWO_HUNDRED){
                        HttpEntity httpEntity = httpResponse.getEntity();
                        String count = EntityUtils.toString(httpEntity,FinalData.CODE);
                        Message message = new Message();
                        message.what = FinalData.ZERO_INT;
                        message.obj = count.toString();
                        handler2.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private List<Content> getCarte(String product){
        try{
            JSONArray jarray = new JSONArray(product);
            List<Content> cartes = new ArrayList<Content>();
            for (int i = 0;i<jarray.length();i++){
                JSONObject obj = new JSONObject(jarray.get(i).toString());
                Content content = new Content();
                content.setOther(obj.getString("m_ct"));
                content.setC_id(obj.getInt("c_id"));
                content.setU_userName(obj.getString("u_userName"));
                content.setC_ct(obj.getString("c_ct"));
                content.setC_num(obj.getInt("c_num"));
                content.setC_sum(obj.getInt("c_sum"));
                cartes.add(content);
            }
            return cartes;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_my_home,null);
        //获得用户名TextView
        userNameTV = (TextView) v.findViewById(R.id.userNameTV);
        userNameTV.setText(userName);

        viewPager = (ViewPager)v.findViewById(R.id.viewpager);

        iSendBtn = (Button)v.findViewById(R.id.iSendBtn);
        iCommentBtn = (Button)v.findViewById(R.id.iCommentBtn);
        commentIBtn = (Button)v.findViewById(R.id.commentIBtn);
        iLaudBtn = (Button)v.findViewById(R.id.iLaudBtn);
        laudIBtn = (Button)v.findViewById(R.id.laudIBtn);
        setTV = (TextView)v.findViewById(R.id.setTV);

        //按钮点击事件
        iSendBtn.setOnClickListener(this);
        iCommentBtn.setOnClickListener(this);
        commentIBtn.setOnClickListener(this);
        iLaudBtn.setOnClickListener(this);
        laudIBtn.setOnClickListener(this);
        setTV.setOnClickListener(this);

        //我发的
        View iSend = inflater.inflate(R.layout.isend,null);
        //初始化控件
        jokeList = (ListView)iSend.findViewById(R.id.jokeList);
        //获得Application中的userName
        String userName = getApp().getUserName();
        isendUrl = Address.ADDRESS+"wofade?u_userName="+userName;
        //调用HttpPostRequest()
        HttpPostRequest(isendUrl);
        //下拉刷新
        mSwipeLayout = (SwipeRefreshLayout) iSend.findViewById(R.id.id_swipe_ly);
        mSwipeLayout.setColorScheme(new int[]{android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light});
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //执行刷新方法
                HttpPostRequest(isendUrl);
            }
        });
        /**
         * 我评的
         */
        View iComment = inflater.inflate(R.layout.icommen,null);
        commentList = (ListView) iComment.findViewById(R.id.commentList);
        icommenUrl = Address.ADDRESS+"wopingde?u_userName="+userName;
        HttpPostRequest1(icommenUrl);
        //下拉刷新
        id_swipe_ly_comment = (SwipeRefreshLayout) iComment.findViewById(R.id.id_swipe_ly_comment);
        id_swipe_ly_comment.setColorScheme(new int[]{android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light});
        id_swipe_ly_comment.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //执行刷新方法
                HttpPostRequest1(icommenUrl);
            }
        });

        /**
         * 评我的
         */
        View commentI = inflater.inflate(R.layout.commenti,null);
        commentIList = (ListView) commentI.findViewById(R.id.commentIList);
        commeniUrl = Address.ADDRESS+"pingwode?u_userName="+userName;
        HttpPostRequest2(commeniUrl);
        //下拉刷新
        id_swipe_ly_commentI = (SwipeRefreshLayout) commentI.findViewById(R.id.id_swipe_ly_commentI);
        id_swipe_ly_commentI.setColorScheme(new int[]{android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light});
        id_swipe_ly_commentI.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //执行刷新方法
                HttpPostRequest2(commeniUrl);
            }
        });

        /**
         * 我赞的
         */
        View iLaud = inflater.inflate(R.layout.ilaud,null);


        /**
         * 赞我的
         */
        View laudI = inflater.inflate(R.layout.laudi,null);



        mViews.add(iSend);
        mViews.add(iComment);
        mViews.add(commentI);
        mViews.add(iLaud);
        mViews.add(laudI);

        mAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return mViews.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object o) {
                return view == o;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = mViews.get(position);
                container.addView(view);
                return view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mViews.get(position));
            }
        };

        viewPager.setAdapter(mAdapter);
        //页面改变监听
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public int CurrentItem;

            //把所有按钮背景变成白色
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onPageSelected(int i) {
                changeBackground();
                CurrentItem = viewPager.getCurrentItem();
                switch (CurrentItem){
                    case 0:
                        iSendBtn.setBackground(getResources().getDrawable(R.drawable.blue_circles_tv));
                        break;
                    case 1:
                        iCommentBtn.setBackground(getResources().getDrawable(R.drawable.blue_circles_tv));
                        break;
                    case 2:
                        commentIBtn.setBackground(getResources().getDrawable(R.drawable.blue_circles_tv));
                        break;
                    case 3:
                        iLaudBtn.setBackground(getResources().getDrawable(R.drawable.blue_circles_tv));
                        break;
                    case 4:
                        laudIBtn.setBackground(getResources().getDrawable(R.drawable.blue_circles_tv));
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }

        });

        return v;
    }


    //点击事件
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View view) {
        //把所有按钮背景变成白色
        changeBackground();
        switch (view.getId()){
            case R.id.iSendBtn:
                viewPager.setCurrentItem(0);
                iSendBtn.setBackground(getResources().getDrawable(R.drawable.blue_circles_tv));
                break;
            case R.id.iCommentBtn:
                viewPager.setCurrentItem(1);
                iCommentBtn.setBackground(getResources().getDrawable(R.drawable.blue_circles_tv));
                break;
            case R.id.commentIBtn:
                viewPager.setCurrentItem(2);
                commentIBtn.setBackground(getResources().getDrawable(R.drawable.blue_circles_tv));
                break;
            case R.id.iLaudBtn:
                viewPager.setCurrentItem(3);
                iLaudBtn.setBackground(getResources().getDrawable(R.drawable.blue_circles_tv));
                break;
            case R.id.laudIBtn:
                viewPager.setCurrentItem(4);
                laudIBtn.setBackground(getResources().getDrawable(R.drawable.blue_circles_tv));
                break;
            case R.id.setTV:
                intent = new Intent(mContext,SettingsActivity.class);
                startActivity(intent);
                break;
        }
    }

    //设置所有按钮背景为白色
    private void changeBackground() {
        iSendBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.white_circles_tv));
        iCommentBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.white_circles_tv));
        commentIBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.white_circles_tv));
        iLaudBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.white_circles_tv));
        laudIBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.white_circles_tv));
    }

    //获取application
    public MyApplication getApp(){
        return (MyApplication) getActivity().getApplication().getApplicationContext();
    }


    //自定义适配器（我发的）
    public class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, final View convertView, ViewGroup parent) {
            final View view = getLayoutInflater(null).inflate(R.layout.jokelist_item,null);

            final Content c = list.get(position);
            ((TextView)view.findViewById(R.id.u_NameTV)).setText(c.getU_userName());
            ((TextView)view.findViewById(R.id.contentTV)).setText(c.getC_ct());
            ((TextView)view.findViewById(laudBtn)).setText(FinalData.LAUD+FinalData.LEFT+c.getC_num()+FinalData.RIGHT);
            //分享按钮点击事件
            view.findViewById(R.id.shareBtn);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(mContext, "分享", Toast.LENGTH_SHORT).show();
                }
            });

            //点赞按钮
            final View laudBtn = ((TextView) view.findViewById(R.id.laudBtn));
            laudBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                        /*url1 = Address.ADDRESS+"updateNum?c_id="+c.getC_id();
                        HttpPostRequest1(url1);*/
                }
            });

            ((TextView)view.findViewById(discussBtn)).setText(FinalData.DISCUSS+FinalData.LEFT+c.getC_sum()+FinalData.RIGHT);

            //评论按钮点击事件
            View discussBtn = ((TextView) view.findViewById(R.id.discussBtn));
            discussBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                        //执行评论
                        //跳转至笑话详情
                        intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putInt("c_id",c.getC_id());//内容id
                        bundle.putString("content", c.getC_ct());//内容
                        bundle.putString("laud", c.getC_num()+"");
                        bundle.putString("discuss",c.getC_sum()+"");
                        intent.setClass(getActivity(),jokeListDetailActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                }
            });

            //笑话内容点击事件
            View contentTV = ((TextView) view.findViewById(R.id.contentTV));
            contentTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                        //跳转至笑话详情
                        intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putInt("c_id",c.getC_id());//内容id
                        bundle.putString("content", c.getC_ct());//内容
                        bundle.putInt("laud", c.getC_num());//赞数量
                        bundle.putInt("discuss",c.getC_sum());//评论数量
                        intent.setClass(getActivity(),jokeListDetailActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                }
            });
            return view;
        }
    }

    //自定义适配器（我评的）
    public class CommentAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, final View convertView, ViewGroup parent) {
            final View view = getLayoutInflater(null).inflate(R.layout.icommen_item,null);

            final Content c = list.get(position);
            ((TextView)view.findViewById(R.id.otherTV)).setText(c.getU_userName()+":");
            ((TextView)view.findViewById(R.id.otherContentTV)).setText(c.getC_ct());
            if (c.getU_userName().equals(userName)){
                ((TextView)view.findViewById(R.id.IsayTV)).setText("我说:");
            }
            ((TextView)view.findViewById(R.id.myCommenTV)).setText(c.getOther());

            return view;
        }
    }

}
